<script setup>
import {ref, onBeforeUnmount, watch, computed} from 'vue';
import {Timer, Clock, Trophy, Star, Play, Pause} from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const TIME_TASKS = [
  {
    id: 1,
    type: 'estimation',
    targetDuration: 3000,
    instruction: 'timePerception.task1.instruction',
    description: 'timePerception.task1.description'
  },
  {
    id: 2,
    type: 'production',
    targetDuration: 5000,
    instruction: 'timePerception.task2.instruction',
    description: 'timePerception.task2.description'
  },
  {
    id: 3,
    type: 'estimation',
    targetDuration: 7000,
    instruction: 'timePerception.task3.instruction',
    description: 'timePerception.task3.description'
  },
  {
    id: 4,
    type: 'reproduction',
    targetDuration: 4000,
    instruction: 'timePerception.task4.instruction',
    description: 'timePerception.task4.description'
  },
  {
    id: 5,
    type: 'production',
    targetDuration: 2000,
    instruction: 'timePerception.task5.instruction',
    description: 'timePerception.task5.description'
  },
  {
    id: 6,
    type: 'bisection',
    targetDuration: 6000,
    instruction: 'timePerception.task6.instruction',
    description: 'timePerception.task6.description'
  },
  {
    id: 7,
    type: 'estimation',
    targetDuration: 10000,
    instruction: 'timePerception.task7.instruction',
    description: 'timePerception.task7.description'
  },
  {
    id: 8,
    type: 'reproduction',
    targetDuration: 8000,
    instruction: 'timePerception.task8.instruction',
    description: 'timePerception.task8.description'
  }
];

const emit = defineEmits(['complete']);

const stage = ref('instructions');
const currentTaskIndex = ref(0);
const taskPhase = ref('instruction');
const isStimulating = ref(false);
const isResponding = ref(false);
const responseStartTime = ref(0);
const estimatedTime = ref(0);
const elapsedTime = ref(0);
const responses = ref([]);
const accuracyScores = ref([]);
const timeLeft = ref(420); // 7分钟
const startTime = ref(0);
const totalScore = ref(0);

const stimulusStartTime = ref(0);
const task = computed(() => TIME_TASKS[currentTaskIndex.value]);

let timerInterval = null;
let timingInterval = null;

const handleStartTest = () => {
  stage.value = 'test';
  startTime.value = Date.now();
  taskPhase.value = 'instruction';
};

const handleStartStimulus = () => {
  taskPhase.value = 'stimulus';
  isStimulating.value = true;
  stimulusStartTime.value = Date.now();

  if (task.value.type === 'bisection') {
    setTimeout(() => {
      isStimulating.value = false;
      setTimeout(() => {
        isStimulating.value = true;
        setTimeout(() => {
          isStimulating.value = false;
          setTimeout(() => {
            isStimulating.value = true;
            setTimeout(() => {
              isStimulating.value = false;
              taskPhase.value = 'response';
            }, task.value.targetDuration);
          }, 1000);
        }, 10000);
      }, 1000);
    }, 2000);
  } else {
    setTimeout(() => {
      isStimulating.value = false;
      if (task.value.type === 'estimation' || task.value.type === 'reproduction') {
        taskPhase.value = 'response';
      }
    }, task.value.targetDuration);
  }
};

const handleGoToResponse = () => {
  taskPhase.value = 'response';
};

const handleStartProduction = () => {
  if (isResponding.value) return;
  isResponding.value = true;
  responseStartTime.value = Date.now();
  timingInterval = setInterval(() => {
    elapsedTime.value = (Date.now() - responseStartTime.value);
  }, 100);

  window.addEventListener('mouseup', handleStopProduction, { once: true });
  window.addEventListener('touchend', handleStopProduction, { once: true });
};

const handleStopProduction = () => {
  if (!isResponding.value) return;
  clearInterval(timingInterval);
  const actualTime = Date.now() - responseStartTime.value;
  estimatedTime.value = actualTime;
  isResponding.value = false;
  processResponse(actualTime);
};

const handleStartReproduction = () => {
  if (isResponding.value) return;
  isResponding.value = true;
  responseStartTime.value = Date.now();
  timingInterval = setInterval(() => {
    elapsedTime.value = (Date.now() - responseStartTime.value);
  }, 100);

  window.addEventListener('mouseup', handleStopReproduction, { once: true });
  window.addEventListener('touchend', handleStopReproduction, { once: true });
};

const handleStopReproduction = () => {
  if (!isResponding.value) return;
  clearInterval(timingInterval);
  const actualTime = Date.now() - responseStartTime.value;
  estimatedTime.value = actualTime;
  isResponding.value = false;
  processResponse(actualTime);
};

const handleTimeEstimation = (estimatedSeconds) => {
  const estimatedMs = estimatedSeconds * 1000;
  estimatedTime.value = estimatedMs;
  processResponse(estimatedMs);
};

const handleBisectionChoice = (choice) => {
  const correct = choice === 'long';
  const score = correct ? 100 : 0;

  responses.value.push(choice === 'short' ? 2000 : 10000);
  accuracyScores.value.push(score);
  totalScore.value += score;

  nextTask();
};

const processResponse = (responseTime) => {
  const targetTime = task.value.targetDuration;
  const absoluteError = Math.abs(responseTime - targetTime);
  const relativeError = absoluteError / targetTime;
  const accuracy = Math.max(0, 100 - (relativeError * 100));

  responses.value.push(responseTime);
  accuracyScores.value.push(accuracy);
  totalScore.value += accuracy;

  taskPhase.value = 'feedback';

  setTimeout(() => {
    nextTask();
  }, 2000);
};

const nextTask = () => {
  if (currentTaskIndex.value < TIME_TASKS.length - 1) {
    currentTaskIndex.value++;
    taskPhase.value = 'instruction';
    isStimulating.value = false;
    isResponding.value = false;
    estimatedTime.value = 0;
  } else {
    stage.value = 'results';
  }
};

const handleComplete = () => {
  const averageAccuracy = Math.round(totalScore.value / TIME_TASKS.length);
  const averageError = responses.value.length > 0 ? Math.round(
    responses.value.reduce((sum, response, index) => {
      const target = TIME_TASKS[index].targetDuration;
      return sum + Math.abs(response - target) / target;
    }, 0) / responses.value.length * 100
  ) : 0;

  const estimationTasks = TIME_TASKS.filter(t => t.type === 'estimation');
  const productionTasks = TIME_TASKS.filter(t => t.type === 'production');
  const reproductionTasks = TIME_TASKS.filter(t => t.type === 'reproduction');

  const getAccuracyForType = (type) => {
    const scores = accuracyScores.value.filter((_, index) => TIME_TASKS[index].type === type);
    return scores.length > 0 ? Math.round(scores.reduce((sum, acc) => sum + acc, 0) / scores.length) : 0;
  };

  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const result = {
    id: Date.now().toString(),
    testType: 'time-perception',
    score: averageAccuracy,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTasks: TIME_TASKS.length,
      averageAccuracy,
      averageError,
      estimationAccuracy: getAccuracyForType('estimation'),
      productionAccuracy: getAccuracyForType('production'),
      reproductionAccuracy: getAccuracyForType('reproduction'),
      timePerceptionIndex: Math.round(100 - averageError),
      totalScore: totalScore.value
    }
  };

  emit('complete', result);
};

const stimulusClasses = computed(() => {
  const stimulusColors = {
    1: 'bg-blue-500',
    3: 'bg-green-500',
    7: 'bg-purple-500'
  };
  const stimulusShapes = {
    1: 'rounded-full',
    3: 'rounded-lg',
    7: 'rounded-none'
  };
  return `w-32 h-32 mx-auto ${stimulusColors[task.value.id] || 'bg-gray-500'} ${stimulusShapes[task.value.id] || 'rounded-full'} shadow-lg`;
});

const finalResult = computed(() => {
  const averageAccuracy = Math.round(totalScore.value / TIME_TASKS.length);
  const averageError = responses.value.length > 0 ? Math.round(
    responses.value.reduce((sum, response, index) => {
      const target = TIME_TASKS[index].targetDuration;
      return sum + Math.abs(response - target) / target;
    }, 0) / responses.value.length * 100
  ) : 0;
  return {averageAccuracy, averageError};
});

watch(stage, (newStage) => {
  if (newStage === 'test' && timeLeft.value > 0) {
    timerInterval = setInterval(() => {
      timeLeft.value--;
      if (timeLeft.value <= 0) {
        clearInterval(timerInterval);
        stage.value = 'results';
      }
    }, 1000);
  } else {
    clearInterval(timerInterval);
  }
});

onBeforeUnmount(() => {
  clearInterval(timerInterval);
  clearInterval(timingInterval);
});

const progress = computed(() => (currentTaskIndex.value / TIME_TASKS.length) * 100);

const start = () => {

}
</script>

<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <Timer class="w-8 h-8 text-white"/>
        </div>
        <CardTitle class="text-2xl text-slate-800">{{ t('timePerception.title') }}</CardTitle>
        <p class="text-slate-600 mt-2">{{ t('timePerception.description') }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div class="bg-gradient-to-r from-orange-50 to-red-50 rounded-xl p-6 border border-orange-100">
          <h3 class="font-semibold text-orange-900 mb-4 flex items-center gap-2">
            <Star class="w-5 h-5"/>
            {{ t('timePerception.instructionsTitle') }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
              <p><strong>{{ t('timePerception.type.estimation') }}</strong>：{{ t('timePerception.type.estimationDescription') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
              <p><strong>{{ t('timePerception.type.production') }}</strong>：{{ t('timePerception.type.productionDescription') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
              <p><strong>{{ t('timePerception.type.reproduction') }}</strong>：{{ t('timePerception.type.reproductionDescription') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
              <p><strong>{{ t('timePerception.type.bisection') }}</strong>：{{ t('timePerception.type.bisectionDescription') }}</p>
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
            <div class="text-2xl font-bold text-orange-600 mb-1">{{ TIME_TASKS.length }}</div>
            <div class="text-sm text-orange-700">{{ t('timePerception.taskCount') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
            <div class="text-2xl font-bold text-red-600 mb-1">4</div>
            <div class="text-sm text-red-700">{{ t('timePerception.taskTypes') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-orange-50 to-red-50 rounded-xl border border-orange-200">
            <div class="text-2xl font-bold text-slate-600 mb-1">{{ Math.floor(timeLeft / 60) }}</div>
            <div class="text-sm text-slate-700">{{ t('timePerception.timeLimitMinutes') }}</div>
          </div>
        </div>

        <Button
          class="w-full bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleStartTest"
        >
          {{ t('timePerception.startButton') }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'test'" class="max-w-4xl mx-auto space-y-6">
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge class="bg-orange-100 text-orange-700 border-orange-300" variant="outline">
          {{ t('timePerception.taskProgress') }} {{ currentTaskIndex + 1 }} / {{ TIME_TASKS.length }}
        </Badge>
        <Badge :class="{
          'bg-blue-100 text-blue-700 border-blue-300': task.type === 'estimation',
          'bg-green-100 text-green-700 border-green-300': task.type === 'production',
          'bg-purple-100 text-purple-700 border-purple-300': task.type === 'reproduction',
          'bg-yellow-100 text-yellow-700 border-yellow-300': task.type === 'bisection'
        }" variant="outline">
          {{
            task.type === 'estimation' ? t('timePerception.type.estimation') :
              task.type === 'production' ? t('timePerception.type.production') :
                task.type === 'reproduction' ? t('timePerception.type.reproduction') : t('timePerception.type.bisection')
          }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4"/>
          <span class="font-semibold">{{ Math.round(totalScore / (currentTaskIndex || 1)) }}</span>
        </div>
      </div>

      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500"/>
        <span :class="['font-mono text-lg font-bold', timeLeft <= 60 ? 'text-red-500' : 'text-slate-700']">
          {{ Math.floor(timeLeft / 60) }}:{{ (timeLeft % 60).toString().padStart(2, '0') }}
        </span>
      </div>
    </div>

    <Progress :model-value="progress" class="h-2"/>

    <Card class="bg-gradient-to-r from-orange-50 to-red-50 border-orange-200">
      <CardContent class="py-4">
        <div class="text-center">
          <h3 class="text-lg font-semibold text-orange-800 mb-2">
            {{ t(task.description) }}
          </h3>
          <p class="text-orange-700">{{ t(task.instruction) }}</p>
        </div>
      </CardContent>
    </Card>

    <Card class="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
      <CardContent class="py-12 min-h-[20rem] flex items-center justify-center">
        <div class="text-center space-y-8 w-full">
          <Transition mode="out-in" name="fade">
            <div v-if="taskPhase === 'instruction'" class="space-y-6">
              <div class="text-xl text-slate-700">{{ t('timePerception.prepareTask') }}</div>
              <Button
                class="bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white px-8 py-3 font-semibold"
                @click="task.type === 'production' ? handleGoToResponse() : handleStartStimulus()"
              >
                <Play class="w-5 h-5 mr-2"/>
                {{ t('timePerception.start') }}
              </Button>
            </div>

            <div v-else-if="taskPhase === 'stimulus'" class="space-y-6">
              <div class="text-lg text-slate-600">
                {{ task.type === 'bisection' ? t('timePerception.bisectionStimulusInstruction') : t('timePerception.stimulusInstruction') }}
              </div>
              <Transition name="fade">
                <div v-if="isStimulating" :class="stimulusClasses"></div>
              </Transition>
            </div>

            <div v-else-if="taskPhase === 'response'" class="space-y-6">
              <div v-if="task.type === 'estimation'" class="space-y-4">
                <div class="text-lg text-slate-700">{{ t('timePerception.estimationQuestion') }}</div>
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 max-w-lg mx-auto">
                  <Button
                    v-for="seconds in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"
                    :key="seconds"
                    class="h-12 hover:bg-orange-50 hover:border-orange-300"
                    variant="outline"
                    @click="() => handleTimeEstimation(seconds)"
                  >
                    {{ seconds }}{{ t('timePerception.secondsUnit') }}
                  </Button>
                </div>
              </div>

              <div v-else-if="task.type === 'production'" class="space-y-4">
                <div class="text-lg text-slate-700">
                  {{ t('timePerception.productionInstruction', { seconds: task.targetDuration / 1000 }) }}
                </div>
                <Button
                  :class="['w-32 h-32 rounded-full text-xl font-bold text-white', isResponding ? 'bg-red-500 hover:bg-red-600' : 'bg-green-500 hover:bg-green-600']"
                  @mousedown.prevent="handleStartProduction"
                  @touchstart.prevent="handleStartProduction"
                >
                  {{ isResponding ? t('timePerception.release') : t('timePerception.hold') }}
                </Button>
                <div v-if="isResponding" class="text-sm text-slate-500">
                  {{ t('timePerception.timing') }} {{ (elapsedTime / 1000).toFixed(1) }}s
                </div>
              </div>

              <div v-else-if="task.type === 'reproduction'" class="space-y-4">
                <div class="text-lg text-slate-700">
                  {{ t('timePerception.reproductionInstruction') }}
                </div>
                <Button
                  :class="['w-32 h-32 rounded-full text-xl font-bold text-white', isResponding ? 'bg-red-500 hover:bg-red-600' : 'bg-purple-500 hover:bg-purple-600']"
                  @mousedown.prevent="handleStartReproduction"
                  @touchstart.prevent="handleStartReproduction"
                >
                  {{ isResponding ? t('timePerception.release') : t('timePerception.hold') }}
                </Button>
                <div v-if="isResponding" class="text-sm text-slate-500">
                  {{ t('timePerception.timing') }} {{ (elapsedTime / 1000).toFixed(1) }}s
                </div>
              </div>

              <div v-else-if="task.type === 'bisection'" class="space-y-4">
                <div class="text-lg text-slate-700">
                  {{ t('timePerception.bisectionQuestion') }}
                </div>
                <div class="flex justify-center gap-6">
                  <Button class="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3"
                          @click="() => handleBisectionChoice('short')">
                    {{ t('timePerception.closerToShort') }}
                  </Button>
                  <Button class="bg-red-500 hover:bg-red-600 text-white px-8 py-3"
                          @click="() => handleBisectionChoice('long')">
                    {{ t('timePerception.closerToLong') }}
                  </Button>
                </div>
              </div>
            </div>

            <div v-else-if="taskPhase === 'feedback'" class="space-y-4">
              <div class="text-lg font-semibold text-slate-800">{{ t('timePerception.feedback') }}</div>
              <div class="bg-slate-100 rounded-lg p-4 max-w-sm mx-auto">
                <div class="text-slate-700">
                  {{ t('timePerception.targetTime') }} {{ task.targetDuration / 1000 }}秒
                </div>
                <div class="text-slate-700">
                  {{ t('timePerception.yourResponse') }} {{ Math.round(estimatedTime / 100) / 10 }}秒
                </div>
                <div class="text-slate-700">
                  {{ t('timePerception.error') }} {{ Math.abs(estimatedTime - task.targetDuration) / 1000 }}秒
                </div>
              </div>
            </div>
          </Transition>
        </div>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-orange-200 shadow-xl">
      <CardHeader class="text-center pb-6">
        <div
          class="w-20 h-20 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <Trophy class="w-10 h-10 text-white"/>
        </div>

        <CardTitle class="text-3xl text-slate-800 mb-2">{{ t('timePerception.testComplete') }}</CardTitle>
        <div class="text-6xl font-bold bg-gradient-to-r from-orange-600 to-red-500 bg-clip-text text-transparent">
          {{ finalResult.averageAccuracy }}
        </div>
        <p class="text-slate-600">{{ t('timePerception.accuracy') }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
            <div class="text-2xl font-bold text-orange-600 mb-1">{{ finalResult.averageError }}%</div>
            <div class="text-sm text-orange-700">{{ t('timePerception.averageError') }}</div>
          </div>
          <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
            <div class="text-2xl font-bold text-red-600 mb-1">{{ Math.round(100 - finalResult.averageError) }}</div>
            <div class="text-sm text-red-700">{{ t('timePerception.perceptionIndex') }}</div>
          </div>
        </div>

        <div class="space-y-3">
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('timePerception.overallAccuracy') }}</span>
            <span class="font-semibold text-slate-800">{{ finalResult.averageAccuracy }}%</span>
          </div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('timePerception.tasksCompleted') }}</span>
            <span class="font-semibold text-slate-800">{{ TIME_TASKS.length }}</span>
          </div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('timePerception.totalScore') }}</span>
            <span class="font-semibold text-slate-800">{{ Math.round(totalScore) }}</span>
          </div>
        </div>

        <Button
          class="w-full bg-gradient-to-r from-orange-600 to-red-500 hover:from-orange-700 hover:to-red-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleComplete"
        >
          {{ t('timePerception.viewDetails') }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
